package smtpserver

import (
	"strings"
)

// InitialState 初始状态
type InitialState struct{}

func NewInitialState() *InitialState {
	return &InitialState{}
}

func (s *InitialState) GetName() string {
	return "INITIAL"
}

func (s *InitialState) HandleCommand(session *Session, command string) error {
	parts := strings.SplitN(command, " ", 2)
	if len(parts) == 0 {
		return session.respond(CODE_SYNTAX_ERROR, "Empty command")
	}

	cmd := strings.ToUpper(parts[0])
	var params string
	if len(parts) > 1 {
		params = parts[1]
	}

	switch cmd {
	case CMD_HELO, CMD_EHLO:
		return session.handleHelo(cmd, params)
	case CMD_AUTH:
		return session.handleAuth(params)
	case CMD_QUIT:
		return session.handleQuit()
	default:
		return session.respond(CODE_BAD_SEQUENCE, "HELO/EHLO first")
	}
}

// AuthenticatedState 已认证状态
type AuthenticatedState struct{}

func NewAuthenticatedState() *AuthenticatedState {
	return &AuthenticatedState{}
}

func (s *AuthenticatedState) GetName() string {
	return "AUTHENTICATED"
}

func (s *AuthenticatedState) HandleCommand(session *Session, command string) error {
	parts := strings.SplitN(command, " ", 2)
	if len(parts) == 0 {
		return session.respond(CODE_SYNTAX_ERROR, "Empty command")
	}

	cmd := strings.ToUpper(parts[0])
	var params string
	if len(parts) > 1 {
		params = parts[1]
	}

	switch cmd {
	case CMD_MAIL:
		return session.handleMail(params)
	case CMD_RCPT:
		return session.handleRcpt(params)
	case CMD_DATA:
		return session.handleData()
	case CMD_RSET:
		return session.handleRset()
	case CMD_VRFY:
		return session.handleVrfy(params)
	case CMD_NOOP:
		return session.handleNoop()
	case CMD_QUIT:
		return session.handleQuit()
	case CMD_STARTTLS:
		return session.handleStartTLS()
	case CMD_AUTH:
		return session.respond(CODE_BAD_SEQUENCE, "Already authenticated")
	default:
		return session.respond(CODE_SYNTAX_ERROR, "Command not recognized")
	}
}
